package nl.vu.few.ibivu.biomodels.client.ui;

import nl.vu.few.ibivu.biomodels.client.event.MessageBroadcastType;
import nl.vu.few.ibivu.biomodels.client.ui.view.MessageView;

import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Widget;
import com.smartgwt.client.types.AnimationEffect;
import com.smartgwt.client.types.Overflow;
import com.smartgwt.client.types.VerticalAlignment;
import com.smartgwt.client.widgets.AnimationCallback;
import com.smartgwt.client.widgets.Img;
import com.smartgwt.client.widgets.Label;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.LayoutSpacer;

public class MessageViewImpl extends HLayout implements MessageView {
	private static final int HEIGHT = 32;
	private Label msg;
	private Img icon;
	private Presenter presenter;
	private Timer timer;
	
	public MessageViewImpl(Presenter presenter, MessageBroadcastType type, String message) {
		this.presenter = presenter;
		this.timer = new Timer() {

			@Override
			public void run() {
				remove();
			}
		};
		
		this.setShowShadow(true);
		this.setHeight(HEIGHT);
		this.setWidth100();
		
		msg = new Label();
		msg.setAutoWidth();
		msg.setLayoutAlign(VerticalAlignment.CENTER);
		msg.setOverflow(Overflow.VISIBLE);
		msg.setWrap(false);
		msg.setContents(message);
		icon = new Img();
		icon.setSize(24);
		icon.setLayoutAlign(VerticalAlignment.CENTER);
		LayoutSpacer spacer = new LayoutSpacer();
		spacer.setWidth(5);
		switch (type) {
		case ERROR:
			this.setStyleName("errorMessageView");
			msg.setStyleName("errorMessageViewLabel");
			icon.setSrc("[SKIN]MessageView/error.png");
			break;
		case INFO:
			this.setStyleName("infoMessageView");
			msg.setStyleName("infoMessageViewLabel");
			icon.setSrc("[SKIN]MessageView/info.png");
			break;
		}
		this.addMember(icon);
		this.addMember(spacer);
		this.addMember(msg);
		
		int position = 0;
		Widget top = presenter.getView();
		if (top != null) {
			position += top.getAbsoluteTop() + HEIGHT;
		}
		this.setPageTop(position);
	}
	
	@Override
	public MessageView display() {
		animateShow(AnimationEffect.WIPE, new AnimationCallback(){

			@Override
			public void execute(boolean earlyFinish) {
				timer.schedule(3000);
				
			}});
		return this;
	}
	
	@Override
	public void remove() {
		animateHide(AnimationEffect.FADE, new AnimationCallback(){

			@Override
			public void execute(boolean earlyFinish) {
				presenter.removeMessage(MessageViewImpl.this);
				MessageViewImpl.this.markForDestroy();
			}});
	}
}